package com.example.config;

import com.example.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Slf4j
public class LoginRedisInterceptor implements HandlerInterceptor {

    /**
     * 前置管理器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断是否需要拦截（ThreadLocal中是否存在用户）
        if (UserHolder.getUser() == null) {
            // 4、不存在，拦截
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"请先登录!\"}");
            log.debug("请您先登录！");
            return false;
        }
        return true;
    }
}
